package com.je.workflow.service.push;

import com.alibaba.fastjson2.JSONObject;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.je.bpm.core.model.BpmnModel;
import com.je.bpm.core.model.config.ProcessRemindTypeEnum;
import com.je.bpm.core.model.config.process.MessageSettingConfigImpl;
import com.je.bpm.core.model.task.KaiteBaseUserTask;
import com.je.bpm.engine.earlyWarning.EarlyWarningPush;
import com.je.bpm.engine.impl.persistence.entity.EarlyWarningEntity;
import com.je.bpm.engine.impl.persistence.entity.TaskEntity;
import com.je.common.base.message.vo.NoticeMsg;
import com.je.common.base.message.vo.PushSystemMessage;
import com.je.common.base.util.DateUtils;
import com.je.common.base.util.SecurityUserHolder;
import com.je.message.rpc.PortalRpcService;
import com.je.message.rpc.SocketPushMessageRpcService;
import com.je.message.vo.WebPushTypeEnum;
import com.je.workflow.service.push.pojo.MessageDTO;
import com.je.workflow.service.user.WorkFlowUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class EarlyWarningPushImpl implements EarlyWarningPush {
    @Autowired
    private WorkFlowUserService workFlowUserService;
    @Autowired
    private PushService pushService;
    @Autowired
    private PortalRpcService portalRpcService;
    @Autowired
    private SocketPushMessageRpcService socketPushMessageRpcService;


    @Override
    public void alertArrivalReminder(BpmnModel bpmnModel, KaiteBaseUserTask kaiteBaseUserTask, EarlyWarningEntity earlyWarningEntity, TaskEntity taskEntity) {
        String title = "预警到期提醒";
        String content = String.format("当前流程【%s】中的【%s】任务，已经达到流程预警期限，该任务创建于【%s】,请关注！",
                bpmnModel.getMainProcess().getName(),
                taskEntity.getName(),
                DateUtils.formatDateTime(taskEntity.getCreateTime()));
        send(bpmnModel, taskEntity, content, title);
    }

    @Override
    public void warningReminder(BpmnModel bpmnModel, KaiteBaseUserTask kaiteBaseUserTask, EarlyWarningEntity earlyWarningEntity, TaskEntity taskEntity) {
        String title = "预警提醒";
        String content = String.format("当前流程【%s】中的【%s】任务，已触发流程预警提醒，该任务创建于【%s】,流程预警到期时间为【%s】,请关注！",
                bpmnModel.getMainProcess().getName(),
                taskEntity.getName(),
                DateUtils.formatDateTime(taskEntity.getCreateTime()),
                DateUtils.formatDateTime(earlyWarningEntity.getProcessingTime())
        );
        send(bpmnModel, taskEntity, content, title);
    }


    private void send(BpmnModel bpmnModel, TaskEntity taskEntity, String content, String title) {
        String associationId = workFlowUserService.getAssociationIdById(taskEntity.getAssignee());
        MessageDTO messageDTO = MessageDTO.build(title, bpmnModel.getMainProcess().getName(),
                "", taskEntity.getBusinessKey(), bpmnModel.getMainProcess().getProcessConfig().getFuncCode());
        //左下角通知弹出框
        List<String> pushType = new ArrayList<>();
        MessageSettingConfigImpl messageSettingConfig = bpmnModel.getMainProcess().getMessageSetting();
        for (ProcessRemindTypeEnum processRemindTypeEnum : messageSettingConfig.getMessages()) {
            pushType.add(processRemindTypeEnum.toString());
        }
        pushService.pushUrgeMsg(associationId, messageDTO, pushType, content, title);
        JSONObject showFuncFormInfo = new JSONObject();
        if (!Strings.isNullOrEmpty(taskEntity.getBusinessKey())) {
            showFuncFormInfo.put("funcCode", bpmnModel.getMainProcess().getProcessConfig().getFuncCode());
            showFuncFormInfo.put("beanId", taskEntity.getBusinessKey());
        }
        NoticeMsg noticeMsg = new NoticeMsg(associationId, workFlowUserService.getUserNameById(taskEntity.getAssignee()),
                workFlowUserService.getUserDeptIdById(taskEntity.getAssignee()), workFlowUserService.getUserDeptNameById(taskEntity.getAssignee()),
                content, title, "MSG", "消息", showFuncFormInfo.toJSONString());
        //添加通知
        portalRpcService.insertNoticeMsg(noticeMsg);
        //添加通知添加又上方的红点
        portalRpcService.insertOrUpdateSign(associationId,
                workFlowUserService.getUserDeptIdById(taskEntity.getAssignee()), WebPushTypeEnum.MSG, "insert");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", "MSG");
        jsonObject.put("type", "MSG_MSG");
        jsonObject.put("data", "");
        jsonObject.put("notify", "");
        PushSystemMessage pushSystemMessage = new PushSystemMessage("MSG", String.valueOf(jsonObject));
        List<String> targetUserIds = new ArrayList<>();
        targetUserIds.add(associationId);
        pushSystemMessage.setTargetUserIds(targetUserIds);
        pushSystemMessage.setSourceUserId(SecurityUserHolder.getCurrentAccountId());
        //发送通知刷新右上角的红点标识
        socketPushMessageRpcService.sendMessage(pushSystemMessage);
        JSONObject jsonObjectMyShare = new JSONObject();
        jsonObjectMyShare.put("code", "COLLECTION");
        jsonObjectMyShare.put("type", "MSG_MSG");
        jsonObjectMyShare.put("data", "");
        jsonObjectMyShare.put("notify", "");
        PushSystemMessage pushSystemMessageMyShare = new PushSystemMessage("", String.valueOf(jsonObjectMyShare));
        pushSystemMessageMyShare.setTargetUserIds(Lists.newArrayList(SecurityUserHolder.getCurrentAccountRealUserId()));
        pushSystemMessageMyShare.setSourceUserId("系统");
        socketPushMessageRpcService.sendMessage(pushSystemMessageMyShare);
    }


}
